import os
import requests
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
import logging

logger = logging.getLogger(__name__)

#第一行是密钥，第二行是api地址
DEEPSEEK_API_KEY = 'sk-d64dc1d3327b49bcba8f383bad2279b8'
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"

# Dify API配置
DIFY_API_KEY = 'app-gsrRtZjDXZzzFsUp8ASinC8s'
DIFY_API_URL = "https://api.dify.ai/v1/chat-messages"
FIXED_CONVERSATION_ID = ""

@csrf_exempt
@require_POST
def chat_with_deepseek(request):
    try:
        logger.info("收到AI聊天请求")

        #请求数据
        data = json.loads(request.body)
        user_message = data.get('message', '')

        if not user_message:
            logger.warning("请求缺少message字段")
            return JsonResponse({'error': 'Message is required'}, status=400)

        #准备请求到DeepSeek API的消息
        messages = [{"role": "user", "content": user_message}]

        #请求头
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {DEEPSEEK_API_KEY}"
        }

        #请求体
        payload = {
            "model": "deepseek-chat",
            "messages": messages,
            "temperature": 0.7,
            "max_tokens": 1000
        }

        logger.debug(f"调用DeepSeek API: {DEEPSEEK_API_URL}")
        logger.debug(f"请求头: {headers}")
        logger.debug(f"请求体: {payload}")

        #发送请求
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=payload)

        #记录API响应状态和内容
        logger.info(f"DeepSeek API响应状态: {response.status_code}")
        logger.debug(f"DeepSeek API响应内容: {response.text}")

        if response.status_code == 200:
            result = response.json()
            ai_reply = result['choices'][0]['message']['content']
            return JsonResponse({'success': True, 'reply': ai_reply})
        else:
            error_detail = response.json().get('error', 'Unknown error')
            logger.error(f"DeepSeek API返回错误: {response.status_code}, {error_detail}")
            return JsonResponse({'error': f"DeepSeek API error: {response.status_code}"}, status=500)

    except json.JSONDecodeError as e:
        logger.error(f"JSON解析错误: {str(e)}")
        return JsonResponse({'error': 'Invalid JSON format'}, status=400)
    except requests.exceptions.RequestException as e:
        logger.error(f"请求异常: {str(e)}")
        return JsonResponse({'error': f'Request exception: {str(e)}'}, status=500)
    except KeyError as e:
        logger.error(f"KeyError: {str(e)}，API响应格式可能与预期不符")
        return JsonResponse({'error': 'Unexpected API response format'}, status=500)
    except Exception as e:
        #捕获异常并记录
        logger.exception("处理请求时未知错误")
        return JsonResponse({'error': str(e)}, status=500)


@csrf_exempt
@require_POST
def chat_with_dify(request):
    try:
        logger.info("收到Dify聊天请求")

        # 解析请求数据
        data = json.loads(request.body)
        user_message = data.get('message', '')
        # 可选：从请求中获取conversation_id，如果没有则使用空字符串（新对话）
        conversation_id = data.get('conversation_id', '')

        if not user_message:
            logger.warning("请求缺少message字段")
            return JsonResponse({'error': 'Message is required'}, status=400)

        # 请求头
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {DIFY_API_KEY}"
        }

        # 请求体
        payload = {
            "inputs": {},
            "query": user_message,
            "response_mode": "blocking",  # 使用阻塞模式，等待完整响应
            "user": "user",
            "auto_generate_name": True
        }

        # 只有当conversation_id存在时才添加到payload中
        if conversation_id:
            payload["conversation_id"] = conversation_id

        logger.debug(f"调用Dify API: {DIFY_API_URL}")
        logger.debug(f"请求头: {headers}")
        logger.debug(f"请求体: {payload}")

        # 发送请求到Dify API
        response = requests.post(DIFY_API_URL, headers=headers, json=payload, timeout=60)

        # 记录API响应状态和内容
        logger.info(f"Dify API响应状态: {response.status_code}")
        logger.debug(f"Dify API响应内容: {response.text}")

        if response.status_code == 200:
            result = response.json()
            # 从响应中提取answer字段作为AI回复
            ai_reply = result.get('answer', '')

            # 记录一些有用的信息
            message_id = result.get('message_id', '')
            returned_conversation_id = result.get('conversation_id', '')
            usage_info = result.get('metadata', {}).get('usage', {})

            logger.info(f"Dify回复成功，message_id: {message_id}, conversation_id: {returned_conversation_id}")
            logger.debug(f"Token使用情况: {usage_info}")

            return JsonResponse({
                'success': True,
                'reply': ai_reply,
                'message_id': message_id,
                'conversation_id': returned_conversation_id
            })
        else:
            # 处理不同的错误状态码
            try:
                error_detail = response.json()
                error_message = error_detail.get('message', 'Unknown error')
                error_code = error_detail.get('code', 'unknown')
                logger.error(f"Dify API返回错误: {response.status_code}, code: {error_code}, message: {error_message}")
                return JsonResponse({
                    'error': f"Dify API error: {response.status_code} - {error_message}"
                }, status=500)
            except json.JSONDecodeError:
                logger.error(f"Dify API返回非JSON错误响应: {response.status_code}, {response.text}")
                return JsonResponse({
                    'error': f"Dify API error: {response.status_code}"
                }, status=500)

    except json.JSONDecodeError as e:
        logger.error(f"JSON解析错误: {str(e)}")
        return JsonResponse({'error': 'Invalid JSON format'}, status=400)
    except requests.exceptions.Timeout as e:
        logger.error(f"请求超时: {str(e)}")
        return JsonResponse({'error': 'Request timeout'}, status=500)
    except requests.exceptions.ConnectionError as e:
        logger.error(f"连接错误: {str(e)}")
        return JsonResponse({'error': 'Connection error'}, status=500)
    except requests.exceptions.RequestException as e:
        logger.error(f"请求异常: {str(e)}")
        return JsonResponse({'error': f'Request exception: {str(e)}'}, status=500)
    except KeyError as e:
        logger.error(f"KeyError: {str(e)}，API响应格式可能与预期不符")
        return JsonResponse({'error': 'Unexpected API response format'}, status=500)
    except Exception as e:
        # 捕获所有其他异常并记录
        logger.exception("处理Dify请求时发生未知错误")
        return JsonResponse({'error': str(e)}, status=500)